import json
def _decode_list(data):
    rv = []
    for item in data:
        if isinstance(item, unicode):
            item = item.encode('utf-8')
        elif isinstance(item, list):
            item = _decode_list(item)
        elif isinstance(item, dict):
            item = _decode_dict(item)
        rv.append(item)
    return rv

def _decode_dict(data):
    rv = {}
    for key, value in data.iteritems():
        if isinstance(key, unicode):
           key = key.encode('utf-8')
        if isinstance(value, unicode):
           value = value.encode('utf-8')
        elif isinstance(value, list):
           value = _decode_list(value)
        elif isinstance(value, dict):
           value = _decode_dict(value)
        rv[key] = value
    return rv

class PerfConfig():
    def __init__(self, conf_file):
        fp = open(conf_file)
        jsobj = json.load(fp, encoding='utf-8', object_hook=_decode_dict)
        fp.close()
        self.jsobj = jsobj
    
    def get_tester(self):
        return self.jsobj["tester"].keys()
    
    def get_instance(self):
        return self.jsobj["instance"].keys()

    def get(self, section, option):
        if section in self.jsobj["tester"]:
             return self.jsobj["tester"][section].get(option, '')
        if section in self.jsobj["instance"]:
             return self.jsobj["instance"][section].get(option, '')
        return self.jsobj[section].get(option, '')

    def getint(self, section, option):
        return int(self.get(section, option))

    def items(self, section):
        if section in self.jsobj["tester"]:
             return self.jsobj["tester"][section]
        if section in self.jsobj["instance"]:
             return self.jsobj["instance"][section]
        return self.jsobj[section]

if __name__ == "__main__":
    cf = PerfConfig("perf.json") 
    print cf.get_tester()
    print cf.get_instance()
    print cf.get("ssh", "server")
    print cf.get("ssh", "port")
    print cf.get("ssh", "username")
    print cf.get("ssh", "password")
    print cf.get("ssh", "timeout")
    print cf.getint("dnsperf", "minq")
    print cf.getint("dnsperf", "maxq")
    print cf.getint("dnsperf", "step")
    print cf.getint("dnsperf", "step")
    print ">>>>>>>>>>>>>>>"
    print cf.get('bind', 'server')
    print cf.getint('bind', 'port')
    print cf.get('bind', 'remotepath')
    print cf.get('bind', 'threadnum')
    print cf.getint('bind', 'checktime')

    print cf.get('maple', 'server')
    print cf.getint('maple', 'port')
    print cf.get('maple', 'remotepath')
    print cf.get('maple', 'threadnum')
    print cf.getint('maple', 'checktime')
    
    print cf.items("single_zone") 
